//
//  YHHomeTableViewController.swift
//  YHWeibo
//
//  Created by 昱含 on 16/5/19.
//  Copyright © 2016年 YuHan. All rights reserved.
//

import UIKit
import SVProgressHUD

private let HomeCellID = "HomeCellID"

class YHHomeTableViewController: YHBaseTableViewController {
    
    let refreshView = YHRefreshControl()
    
//    lazy var statuses: [YHStatus] = [YHStatus]()
    lazy var statusListViewModel : YHStatusListViewModel = YHStatusListViewModel()
    override func viewDidLoad() {
        super.viewDidLoad()
        if !userLogin {
            visitorLoginView.setVisitorInfo("关注一些人,回到这里看看有什么惊喜", imageName: "visitordiscover_feed_image_smallicon", isHome: true)
            return
        }
        
        setNavBar()
        
        prepareForTableView()
        
        loadHomeData()
    }
    
    //注册cell
    private func prepareForTableView() {
        
        tableView.registerClass(YHStatusCell.self, forCellReuseIdentifier: HomeCellID)
        
//        tableView.rowHeight = 300
        
        tableView.estimatedRowHeight = 300
        
        tableView.separatorStyle = .None
        
        self.tableView.addSubview(refreshView)
        
        self.navigationController?.navigationBar.addSubview(tipLabel)
        self.navigationController?.navigationBar.insertSubview(tipLabel, atIndex: 0)
        
        refreshView.addTarget(self, action: #selector(self.loadHomeData), forControlEvents: .ValueChanged)
        
//        refreshControl = UIRefreshControl()
//        
//        refreshControl?.addTarget(self, action: #selector(self.loadHomeData), forControlEvents: .ValueChanged)
        
        tableView.tableFooterView = pullupView
    }
    
      override func viewWillLayoutSubviews() {
        
    }
    
    private func setNavBar() {
        
        let popItem = UIBarButtonItem(imageName: "navigationbar_pop", target: self, action: #selector(YHHomeTableViewController.push))
        
        navigationItem.rightBarButtonItem = popItem
    }
    
    @objc private func push() {
        let detailVC = YHDetailViewController()
//        detailVC.hidesBottomBarWhenPushed = true
        navigationController?.pushViewController(detailVC, animated: true)
        
    }
    
    //添加菊花控件,避免上拉下拉刷新冲突问题
    private lazy var pullupView: UIActivityIndicatorView = {
        
        let indicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
        return indicatorView
    }()
    
    private lazy var tipLabel: UILabel = {
       
        let l = UILabel(title: "", font: 15, textColor: UIColor.whiteColor())
        l.frame = CGRect(x: 0, y: -64, width: screenWidth, height: 40)
        l.backgroundColor = UIColor.orangeColor()
        l.alpha = 0.8
        return l
    }()

}

extension YHHomeTableViewController {
    
    @objc private func loadHomeData() {
        
        statusListViewModel.loadHomeData(pullupView.isAnimating()){ (isSuccess,count) in
            
            if self.pullupView.isAnimating(){
                
                self.pullupView.stopAnimating()
            }else{
                self.startAnimation(count)
            }
            
            self.refreshView.endRefreshing()
            
            if !isSuccess {
                 SVProgressHUD.showErrorWithStatus(appErrorTip)
                return
            }
            self.tableView.reloadData()
        }
        
    }
    
    private func startAnimation(count: Int){
        
        let tipText = (count == 0) ? "没有新微博" : "有\(count)条新微博"
        tipLabel.text = tipText
        let rect = tipLabel.frame
        
        UIView.animateWithDuration(0.6, animations: { 
            self.tipLabel.frame = CGRect(x: 0, y: 44, width: screenWidth, height: 40)
            }) { (_) in
                UIView.animateWithDuration(0.3, delay: 1, options: [], animations: { 
                    self.tipLabel.frame = rect
                    }, completion: { (_) in
                        print("ok")
                })
        }
        
    }
    
    

}

extension YHHomeTableViewController {
    
    // MARK: - Table view data source
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return statusListViewModel.statusViewModelArray.count
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCellWithIdentifier(HomeCellID, forIndexPath: indexPath) as! YHStatusCell
        
        if indexPath.row == statusListViewModel.statusViewModelArray.count - 1 && !pullupView.isAnimating(){
            
            print("静默加载",pullupView.isAnimating())
            pullupView.startAnimating()
            
            loadHomeData()
        }
//        cell.textLabel?.text = statuses[indexPath.row].user?.name
        cell.statusViewModel = statusListViewModel.statusViewModelArray[indexPath.row]
//        print(statusListViewModel.statusViewModelArray[indexPath.row].status?.retweeted_status?.text)
        return cell
        
    }

}
